// pages/messageInfo/messageInfo.js
import TIM from '../../utils/tim-wx.js';
let md5 = require("../../utils/md5.js")
let axios = require("../../utils/util.js")
import {
  IMSDK
} from '../../utils/common';
const app = getApp()
const myaudio = wx.createInnerAudioContext() //音频
Page({
  /** 
   * 页面的初始数据
   */
  data: {
    bottomHeight: 20, //定义comment容器与page容器下边界之间的距离
    statusBarHeight: '44',
    statusBarHeight2: '120px',
    nextReqMessageID: '', //下拉分页码
    loading: true,
    suspend: false, //暂停状态
    voice_index: '', //值播放语音状态下标
    Sum_: 0,
    LoadMore: false, //是否显示加载更多 
    heiingdang: false, //黑名单列表
    scrollTop: '', //高度
    messageList: [], //信息合集
    inputMessage: '', //发送消息
    message_list: {
      userProfile: {}
    }, //跳转获取信息
    messageList_jihe: [], //聊天信息合集
    ImageBitmap: {}, //自己信息
    tim: null,
    isfollow: 0, //是否关注 1已关注 0未关注
    to_user_id: "", //对方id

    scrolTop: 0,
    old: {
      scrolTop: 0,
    },
    oldheight: 0, //标签位置
    newheight: 0 //新窗口高度
  },
  // 点击头像去个人主页
  toperson(data) {
    let user_id = data.currentTarget.dataset.user_id
    console.log(user_id);
    this.conversion(user_id)

  },
  // 获取焦点 唤起软键盘
  bindfocus(e) {
    // console.log('键盘弹起')
    // console.log(e, '键盘弹起')
    this.setData({
      bottomHeight: e.detail.height //将键盘的高度设置为comment容器与page容器下边界之间的距离。
    })
  },
  // 失去焦点 
  bindblur(e) {
    // console.log('收起键盘')
    // console.log(e, '收起键盘')
    this.setData({
      bottomHeight: 20
    })
  },
  //滚动
  bindscroll_(e) {
    // let scroolTop = event.detail.scrollTop;
    // let scrollHeight = event.detail.scrollHeight;
    // let viewHeight = scrollHeight - scroolTop;
    // console.log(scroolTop);
    // console.log(scrollHeight);
    // console.log(viewHeight);

  },
  bindscroll() {
    let _ = this;
    let promise = _.data.tim.getMessageList({
      conversationID: _.data.message_list.conversationID,
      nextReqMessageID: _.data.nextReqMessageID

    });
    promise.then((imResponse) => {
      const messageList = imResponse.data.messageList; // 消息列表。
      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
      console.log(imResponse);
      if (isCompleted) {
        wx.showToast({
          title: "没有更多信息",
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
      setTimeout(() => {
        _.setData({
          messageList: [...messageList, ...this.data.messageList],
          nextReqMessageID: nextReqMessageID,
          loading: false,
        })

      }, 1000)
    });
  },
  personMore() {
    let _ = this
    wx.showActionSheet({
      itemList: [_.data.heiingdang ? '取消拉黑' : '拉黑'],
      success(res) {
        if (res.tapIndex === 0) {
          console.log('拉黑');
          _.devBlackList()
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  heiingdang() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/blacklist",
      data: params
    }).then((res) => {
      let _ = this
      var result = res.data.result.some(function (item) {
        if (item.perfectNumber == _.data.message_list.userProfile.userID) {
          return true
        }
      })
      _.setData({
        heiingdang: result
      })
    })
  },
  devBlackList() {
    let type;
    if (this.data.heiingdang) {
      type = '2'
    } else {
      type = '1'
    }
    let params = {
      type: type,
      memberId: this.data.to_user_id,
    };
    axios.axios({
      url: "/user/editblack", 
      data: params
    }).then((res) => {
      console.log(res.data),
        wx.showToast({
          title: res.data.text,
          icon: 'none'
        })
      this.heiingdang()
    })
  },
  bindMessageInput(e) {
    this.setData({
      inputMessage: e.detail.value
    })
  },
  click_button() {
    getApp().preventActive(() => { //防止多次点击
      if (!this.data.inputMessage) {
        return wx.showToast({
          title: "消息内容不能为空",
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
      let message = this.data.tim.createTextMessage({
        to: this.data.message_list.userProfile.userID.toString(),
        conversationType: TIM.TYPES.CONV_C2C,
        payload: {
          text: this.data.inputMessage
        },
      });
      this.setData({
        inputMessage: '',
      })
      // 2. 发送消息
      let promise = this.data.tim.sendMessage(message);
      promise.then((imResponse) => {
        console.log(imResponse);
        this.setData({
          inputMessage: '',
        })
        this.allInformation()
      }).catch((imError) => {
        // 发送失败
        console.warn('sendMessage error:', imError);
      });
    })
  },
  copyNotice: function (e) {
    console.log("所复制的通知内容：", e.currentTarget.dataset.content);
    wx.setClipboardData({
      data: e.currentTarget.dataset.content,
      success: function (res) {
        wx.getClipboardData({
          success: function () {
            wx.showToast({
              title: '复制成功',
              icon: 'none',
              duration: 2000 //持续的时间
            })
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // authCheck(context);
    this.isfollow()

  },

  //消息合集回调
  allInformation() {
    let promise = this.data.tim.getMessageList({
      conversationID: this.data.message_list.conversationID,
      count: 15,
    });
    promise.then((imResponse) => {
      const messageList = imResponse.data.messageList; // 消息列表。
      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
      console.log(imResponse);
      this.setData({
        nextReqMessageID: nextReqMessageID,
        messageList: messageList
      })
      this.goToBottom(this.data.messageList.length)
    });
  },
  back_hist() {
    wx.navigateBack({
      delta: 1
    })
  },
  // 转化userid
  conversion(conversion) {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: app.globalData.user_id,
      perfectNumber: conversion,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      userId: app.globalData.user_id,
      perfectNumber: conversion,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/message/isfollow",
      data: params
    }).then((res) => {
      wx.navigateTo({
        url: '/pages/me/me?memberId=' + res.data.result.to_user_id,
      })
    })
  },
  //是否关注
  isfollow() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: app.globalData.user_id,
      perfectNumber: this.data.message_list.userProfile.userID,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      userId: app.globalData.user_id,
      perfectNumber: this.data.message_list.userProfile.userID,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/message/isfollow",
      data: params
    }).then((res) => {
      // console.log(res.data),
      this.setData({
        to_user_id: res.data.result.to_user_id,
        isfollow: res.data.result.is_follow
      })
    })
  },
  //关注或取消
  followInsert(e) {
    let isfollow = e.currentTarget.dataset.isfollow;
    // console.log(isfollow);
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: app.globalData.user_id,
      followId: this.data.to_user_id,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      userId: app.globalData.user_id,
      followId: this.data.to_user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: isfollow,
      data: params
    }).then((res) => {
      console.log(res.data.status)
      if (res.data.status == 0) {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        this.isfollow()
      }
    })
  },
  voice(data) {
    let url = data.currentTarget.dataset.voiceurl[0]
    let index = data.currentTarget.dataset.voiceurl[1]
    this.setData({
      suspend: !this.data.suspend
    })
    if (this.data.voice_index == index) {
      //第二次点击同一个
      if (this.data.suspend) {
        myaudio.play(); //开始播放 
      } else {
        myaudio.pause() //暂停
      }
    } else {
      this.setData({
        voice_index: index
      })
      myaudio.src = url;
      myaudio.play(); //开始播放 
    }
  },
  //点击信息进入聊天
  index_() {
    this.data.tim.setMessageRead({
      conversationID: this.data.message_list.conversationID
    });
    this.data.tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, (event) => { //已读回执
      console.log(event);
      this.goToBottom(this.data.messageList.length)
    });
    this.data.tim.on(TIM.EVENT.MESSAGE_RECEIVED, (event) => { //接收成功
        console.log(event.data[0]);
        if (this.data.message_list.conversationID == event.data[0].conversationID) {
          this.setData({
            messageList: [...this.data.messageList, event.data[0]],
          })
          this.goToBottom(this.data.messageList.length)
        }
      }),
      this.allInformation()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options_) {
    let that = this;
    wx.getSystemInfo({
      success: res => {
        that.setData({
          statusBarHeight: res.statusBarHeight,
          statusBarHeight2: res.statusBarHeight+34+'px',
        })
      },
    });
    myaudio.onPlay(() => { //开始播放
      console.log("开始的回调");
    })
    myaudio.onPause((res) => { //暂停播放
      console.log('暂停播放回调!');
    })
    myaudio.onEnded((res) => { //结束播放
      this.setData({
        voice_index: "",
        suspend: false
      })
      console.log("结束的回调");
    })
    let user_list = wx.getStorageSync('UserInformation');
    let tim;
    tim = IMSDK(this, user_list.token)
    that.setData({
      tim
    })
    if (options_.index) { //消息页聊天
      let data = decodeURIComponent((options_.index)); // decodeURIComponent（）加上该方法
      let message_list = JSON.parse(data);
      console.log(wx.getStorageSync('UserInformation'));
      that.setData({
        message_list: message_list,
        ImageBitmap: wx.getStorageSync('UserInformation')
      })
      that.isfollow()
    } else if (options_.system) { //房间私聊
      console.log(JSON.parse(options_.system));
      let system = JSON.parse(options_.system)
      let message_list = {
        "userProfile": {
          "nick": system.nickname,
          "userID": system.perfect_number.toString()
        },
        "conversationID": 'C2C' + system.perfect_number
      }
      that.setData({
        message_list: message_list,
        ImageBitmap: wx.getStorageSync('UserInformation')
      })
      that.isfollow()
    } else if (options_.customerService) { //客服中心
      let customerService = JSON.parse(options_.customerService)
      // console.log(options_.customerService);
      let message_list = {
        "userProfile": {
          "nick": '官方客服',
          "userID": customerService.toString(),
        },
        "conversationID": 'C2C' + customerService
      }
      that.setData({
        message_list: message_list,
        ImageBitmap: wx.getStorageSync('UserInformation')
      })
      that.isfollow()
    } else if (options_.Hi) { //首页Hi
      let data = decodeURIComponent((options_.Hi)); // decodeURIComponent（）加上该方法
      let message_list_ = JSON.parse(data);
      console.log(message_list_);
      let message_list = {
        "userProfile": {
          "nick": message_list_.nickname,
          "userID": message_list_.perfect_number,
        },
        "conversationID": 'C2C' + message_list_.perfect_number
      }
      that.setData({
        message_list: message_list,
        ImageBitmap: wx.getStorageSync('UserInformation')
      })
      that.isfollow()
    } else if (options_.perfect_number) { //个人主页聊一聊
      let data = decodeURIComponent((options_.perfect_number)); // decodeURIComponent（）加上该方法
      let message_list_ = JSON.parse(data);
      let message_list = {
        "userProfile": {
          "nick": message_list_.nickName,
          "userID": message_list_.perfect_number,
        },
        "conversationID": 'C2C' + message_list_.perfect_number
      }
      that.setData({
        message_list: message_list,
        ImageBitmap: wx.getStorageSync('UserInformation')
      })
      that.isfollow()
    } else if (options_.message_info) { //房间私聊
      let data = decodeURIComponent((options_.message_info)); // decodeURIComponent（）加上该方法
      let message_list_ = JSON.parse(data);
      let message_list = {
        "userProfile": {
          "nick": message_list_.nickName,
          "userID": message_list_.perfect_number,
        },
        "conversationID": 'C2C' + message_list_.perfect_number
      }
      that.setData({
        message_list: message_list,
        ImageBitmap: wx.getStorageSync('UserInformation')
      })
      that.isfollow()
    } else if (options_.list_xd) { //好友私聊
      let data = decodeURIComponent((options_.list_xd)); // decodeURIComponent（）加上该方法
      let message_list_ = JSON.parse(data);
      console.log(message_list_);
      let message_list = {
        "userProfile": {
          "nick": message_list_.nickname,
          "userID": message_list_.perfect_number,
        },
        "conversationID": 'C2C' + message_list_.perfect_number
      }
      that.setData({
        message_list: message_list,
        ImageBitmap: wx.getStorageSync('UserInformation')
      })
      that.isfollow()
    }
    that.index_()
    that.heiingdang()
  },
  scrollTop_length(e) { //消息自动下拉
    let query = wx.createSelectorQuery().in(this)
    query.select('#room_chat_list').boundingClientRect((res) => {
      console.log('res: ', res)
      this.setData({
        scrollTop: res.height
      })
    }).exec()

  },

  // 容器滚动到底部
  goToBottom(len) {   
    console.log("发送消息");
    this.setData({
      scrollTop: 100 * len
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.setData({
    //   messageList: JSON.parse(wx.getStorageSync('messageList'))
    // })
  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.data.tim.setMessageRead({
      conversationID: this.data.message_list.conversationID
    });
    this.data.tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, (event) => { //发送成功已读回执
      console.log(event);
      this.goToBottom(this.data.messageList.length)
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
